/* eslint-disable react/jsx-handler-names */
/* eslint-disable max-lines */
import { message } from 'antd';
import { connect } from 'dva';
import _ from 'lodash';
import React, { PureComponent } from 'react';

import AddRuleC from './addRule';
import dictData from './config';

import { TableC, DATA_ENTRY, AdvancedSearch, ContentPackage, PrimaryC } from '../../../components';
import { getUserInfo, isZiGuanEvir } from '../../../utils/commonFunc';
import { showValue2 } from '../../PortfolioManagement/utils';

function showValueForNewEnum(key, dictMap, value) {
  const values = dictMap[key];
  if (!values) return '';
  let text = '';
  values.forEach((item) => {
    if (item.code == value) text = item.value;
  });
  return text;
}
class LimitSetting extends PureComponent {
  state = {
    operateType: undefined, // 新增-1 编辑-2
    record: undefined, // 编辑某一行数据
    productList: [], // 产品下拉
    NewcontrolValues: [],
    admin: undefined, // 是否是管理员
    pageStatus: 1, // 默认列表页1 新增/编辑 2
    currentPage: 1, // 当前页码
    pageSize: 10, // 每页数量
    isReset: false, // 是否点击重置
    productData: [], // 产品下拉
  };

  formAdvRef = React.createRef();

  componentDidMount() {
    const { dispatch } = this.props;
    // 获取表格列表
    this.setState(
      {
        currentPage: 1,
        numInPage: 10,
        isReset: false,
      },
      () => {
        this.getTableList();
      },
    );
    const {
      globalM: { dataDictionary },
    } = this.props;
    // 进入页面，先查一下需要用到的字典吧
    dispatch({
      type: 'limitSetting/save',
      payload: {
        dictMap: dataDictionary,
      },
    });
    // 查询新增下的产品下拉
    dispatch({
      type: 'limitSetting/fetchRootNode',
      payload: {
        createdBy: localStorage.getItem('antd-pro-userId'),
        due: 1,
      },
    }).then((res) => {
      if (res && res.success) {
        const arr1 = _.cloneDeep(res.data || []);
        const arrQuery = _.cloneDeep(res.data || []); // 查询需要的
        const arr0 = [
          { value: 'ALL', title: '全选当前存续产品' },
          { value: 'KFLC', title: '开放式理财产品' },
          { value: 'FBLC', title: '封闭式理财产品' },
          { value: 'XJGL', title: '现金管理类产品' },
          { value: 'GDSY', title: '固定收益类产品' },
          { value: 'GMLC', title: '公募理财产品' },
          { value: 'KFGMLC', title: '开放式公募理财产品' },
          { value: 'DKCP', title: '定开产品' },
          { value: 'OTHERKFSGMLCCP', title: '其他开放式公募理财产品' },
        ];
        const tempKeys = arr0.map((item) => item.value);
        const arr = arr0.concat(arr1);
        arr.map((item) => {
          if (tempKeys.indexOf(item.value) < 0) item.title = `${item.value}-${item.title}`;
        });
        arrQuery.map((item) => {
          item.title = `${item.value}-${item.title}`;
        });
        this.props.dispatch({
          type: 'limitSetting/save',
          payload: {
            productList: arr,
          },
        });
        this.setState({ productData: _.cloneDeep(arrQuery) });
      } else {
        this.props.dispatch({
          type: 'limitSetting/save',
          payload: {
            productList: [],
          },
        });
        this.setState({ productData: [] });
      }
    });
  }

  componentWillUnmount() {
    // 离开前清空缓存数据
    this.props.dispatch({
      type: 'limitSetting/save',
      payload: {
        dictMap: {},
        productSelect: [],
        RootNode: [],
        productList: [],
        conditionOriginList: [],
      },
    });
  }

  onEditItem = (item, type) => {
    const switchList = _.cloneDeep(dictData.switchList);
    this.props.dispatch({
      type: 'limitSetting/queryRuleDatail',
      payload: {
        ruleId: item.ruleId,
      },
      callback: (data) => {
        if (data) {
          const record = data;
          for (const key in record) {
            // 交易方向选中 回填
            // eslint-disable-next-line no-loop-func
            switchList.map((item) => {
              if (item.value === key) {
                item.checked = record[key];
              }
            });
            if (key == 'appliedProductScope') {
              // 表单产品初始化 全部需要转换
              record[key] = this.formateData(record[key]);
            }
          }
          record.switchList = switchList;
          // 拿到数据 翻译成中文
          const formatData = (arr) => {
            if (arr?.length) {
              arr.map((x) => {
                // eslint-disable-next-line no-shadow
                x.conditionList?.map((item) => {
                  item.controlValueName = item.controlValueName?.indexOf('[') > 0 ? JSON.parse(item.controlValueName) : item.controlValueName;
                  if (item.conditionList?.length) formatData(item);
                });
              });
            }
          };
          formatData(record.riskIndexs);
          record.type = type;
          // console.log(record.riskIndexs)
          this.setState({
            operateType: 2,
            record,
            pageStatus: 2,
          });
        }
      },
    });
  };

  // 若选中项为全部，初始化全部数据选中
  formateData = (val) => {
    const {
      limitSetting: { productList },
    } = this.props;
    if (val) {
      const all = val.filter((item) => item === 'ALL');
      if (all && all.length) {
        productList.map((item) => {
          if (item.value !== 'ALL') item.disabled = true;
        });
        this.props.dispatch({
          type: 'limitSetting/save',
          payload: {
            productList,
          },
        });
      } else {
        productList.map((item) => {
          if (item.value !== 'ALL') item.disabled = false;
        });
        this.props.dispatch({
          type: 'limitSetting/save',
          payload: {
            productList,
          },
        });
      }
      return all && all.length ? ['ALL'] : val;
    }
  };

  // 获取限额设置列表
  getTableList = () => {
    const { dispatch } = this.props;
    const { pageSize, currentPage, isReset } = this.state;
    const params = this.formAdvRef.current.formRef.current.getFieldsValue();
    const value = {
      productCodeList: params.search_productCodeList?.length ? params.search_productCodeList : undefined,
      ruleDesc: params.search_ruleDesc || undefined,
      ruleApplyObj: params.search_ruleApplyObj?.length ? params.search_ruleApplyObj : undefined,
      ordinance: params.ordinance?.length ? params.ordinance : undefined, // 监管法规  string
      riskCategory: params.riskCategory?.length ? params.riskCategory : undefined, // 风险类型 string[]
      riskLevel: params.riskLevel?.length ? Number(params.riskLevel) : undefined, // 风险等级 int
      pageNumber: currentPage,
      pageSize,
    };
    if (isReset) {
      message.warning('您已重置查询字段，请设置条件后执行查询');
      return;
    }
    dispatch({
      type: 'limitSetting/fetch',
      payload: value,
    });
  };

  // table点击删除
  onDeleteItem = (id) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'limitSetting/deleteRule',
      payload: {
        ruleId: id,
      },
    }).then((response) => {
      if (response) {
        this.setState(
          {
            currentPage: 1,
            pageSize: 10,
            isReset: false,
          },
          () => {
            this.getTableList();
          },
        );
      }
    });
  };

  // table分页
  onTableChange = (pagination) => {
    const { current, pageSize } = pagination;
    this.setState(
      {
        currentPage: current,
        pageSize,
      },
      () => {
        this.getTableList();
      },
    );
  };

  // 点击新建
  handleAddCurb = () => {
    this.setState({
      operateType: 1,
      record: undefined, // 新增时 选中行清空
      pageStatus: 2,
    });
  };

  // 根据value查找title
  findTitleByValue = (type, val) => {
    let text = '--';
    dictData[type].map((item) => {
      if (item.value == val) text = item.title;
    });
    return text;
  };

  // 渲染表格
  renderCurbTable() {
    const {
      limitSetting: { list, pagination, dictMap, columns: columnsProps },
      loading,
    } = this.props;
    const columns = _.cloneDeep(columnsProps);

    columns.map((item) => {
      if (item.key === 'riskLevel') {
        item.render = (val) => <span>{val !== null ? showValueForNewEnum('riskLevel', dictMap, val) : '--'}</span>;
      }
      if (item.key === 'riskCategory') {
        item.render = (val) => <span>{val !== null ? showValueForNewEnum('riskCategory', dictMap, val) : '--'}</span>;
      }
      if (item.key === 'ruleDesc') {
        item.ellipsis = true;
      }
      if (item.key !== 'ruleDesc' && item.key !== 'operate') {
        item.width = 80;
        if (item.key === 'effectiveTime' || item.key === 'expireTime') {
          item.width = 110;
        }
      }
      if (item.key === 'ruleApplyObj') {
        item.render = (text) => this.findTitleByValue('applyObj', text);
      }
      if (item.key === 'ruleState') {
        item.render = (text) => this.findTitleByValue('falseOrTrue', text);
      }
      if (item.key === 'compareMethod') {
        item.render = (val) => <span>{val !== null ? showValue2('risk_value_compare_method', dictMap, val.toString()) : '--'}</span>;
      }
      // 监管法规render处理
      if (item.key === 'ordinance') {
        item.width = 160;
        item.render = (val) => <span>{val !== null ? showValueForNewEnum('riskOrdinance', dictMap, val) : '--'}</span>;
      }
    });
    if (this.isAdmin() && columns.length && columns[columns.length - 1].key !== 'operate') {
      const item = {};
      item.width = 150;
      item.type = 'operate';
      item.title = '操作';
      item.dataIndex = 'operate';
      item.key = 'operate';
      item.operates = [
        {
          title: '复制',
          onClick: (record) => this.onEditItem(record, 'copy'),
        },
        {
          title: '编辑',
          onClick: (record) => this.onEditItem(record),
        },
        {
          title: '删除',
          onClick: (record) => this.onDeleteItem(record.ruleId),
        },
      ];
      columns.push(item);
    }
    return (
      <div>
        <TableC
          columns={columns}
          dataSource={list ? list.dataSource : []}
          onChange={this.onTableChange}
          rowKey='ruleId'
          loading={loading.effects[`limitSetting/fetch`] === true}
          current={this.state.currentPage}
          total={pagination && pagination.total}
          pageSize={this.state.pageSize}
          selfScrollY={true}
          scroll={{ x: 1600 }} // 设置滚动宽度，否则自适应 没有设置宽的那一列会被挤掉 或者很窄很窄
        />
      </div>
    );
  }

  // 判断是否是管理员
  isAdmin = () => {
    const { admin } = this.state;
    const temp = isZiGuanEvir() ? admin : getUserInfo().isTenantAdmin;
    return temp;
  };

  // 搜索栏
  renderForm() {
    const {
      limitSetting: { dictMap = [] },
    } = this.props;
    function mapEnum(arr) {
      const temp = [];
      if (!arr) return temp;
      arr.map((item) => {
        temp.push({
          title: item.value,
          value: item.code,
        });
      });
      return temp;
    }
    // 监管法规dataSource
    const regulationsArr = dictMap.riskOrdinance ? mapEnum(dictMap.riskOrdinance) : [];
    const riskLevelArr = dictMap.riskLevel ? mapEnum(dictMap.riskLevel) : [];
    const riskCategoryArr = dictMap.riskCategory ? mapEnum(dictMap.riskCategory) : [];
    const searchProps = {
      dataSource: [
        {
          dataIndex: 'search_ruleDesc',
          title: '风险说明',
          type: DATA_ENTRY.INPUT,
        },
        {
          dataIndex: 'search_ruleApplyObj',
          title: '作用范围',
          type: DATA_ENTRY.SELECT,
          dataSource: dictData.applyObj,
          allowClear: true,
          isMultiple: true,
        },
        {
          dataIndex: 'riskCategory',
          title: '风险类型',
          type: DATA_ENTRY.SELECT,
          dataSource: riskCategoryArr,
          allowClear: true,
          isMultiple: true,
        },
        {
          dataIndex: 'riskLevel',
          title: '风险等级',
          type: DATA_ENTRY.SELECT,
          dataSource: riskLevelArr,
          allowClear: true,
        },
        {
          dataIndex: 'ordinance',
          title: '监管法规',
          type: DATA_ENTRY.SELECT,
          dataSource: regulationsArr,
          allowClear: true,
        },
        {
          dataIndex: 'search_productCodeList',
          title: '产品',
          type: DATA_ENTRY.SELECT,
          dataSource: this.state.productData,
          isMultiple: true,
          allowClear: true,
          filterOption: (input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0,
          showSearch: true,
          getValueFromEvent: this.controlValueChange,
        },
      ],
      onRef: (ref) => {
        this.formAdvRef.current = ref;
      },
      onQuery: () => {
        this.setState(
          {
            currentPage: 1,
            pageSize: 10,
            isReset: false,
          },
          () => {
            this.getTableList();
          },
        );
      },
      onClear: () => {
        this.setState({
          isReset: true,
        });
      },
    };
    return (
      <div style={{ marginBottom: '15px' }}>
        <AdvancedSearch {...searchProps} />
      </div>
    );
  }

  // 子页面点击了 取消
  onCancle = () => {
    const {
      limitSetting: { productList },
    } = this.props;
    this.setState({
      pageStatus: 1,
      record: undefined,
      operateType: undefined,
    });
    productList.map((item) => {
      if (item.value !== 'ALL') item.disabled = false;
    });
    this.props.dispatch({
      type: 'limitSetting/save',
      payload: {
        productList,
      },
    });
    console.log('取消');
  };

  // 子页面点击了 确定 刷新列表
  onOk = () => {
    this.setState(
      {
        pageStatus: 1,
        currentPage: 1,
        numInPage: 10,
        isReset: false,
        record: undefined,
        operateType: undefined,
      },
      () => {
        this.getTableList();
      },
    );
  };

  // 分子分母变 修改detailData
  changeDetailData = (riskIndexs = []) => {
    const { record = {} } = this.state;
    record.riskIndexs = [...riskIndexs];
    this.setState({
      record: { ...record },
    });
  };

  /*
      产品组件
      列表结构，默认插入第一条数据“全选当前存续产品和新增产品”（替代“全部”）
      支持多选（选了第一条数据，后面的就不给选了）
      下拉数据中不包含到期产品
    */
  // 产品变更
  controlValueChange = (val) => {
    const { productData } = this.state;
    const arr = val && val.filter((item) => item === 'ALL');
    if (arr && arr.length) {
      productData.map((item) => {
        if (item.value !== 'ALL') item.disabled = true;
      });
      this.setState({
        productData: [...productData],
      });
      return val.filter((item) => item === 'ALL');
    }
    productData.map((item) => {
      if (item.value !== 'ALL') item.disabled = false;
    });
    this.setState({
      productData: [...productData],
    });
    return val;
  };

  render() {
    const { pageStatus, record, operateType } = this.state;
    return (
      <ContentPackage
        title='限额设置'
        contentHtml={
          <div>
            <div style={{ display: pageStatus == 1 ? 'inherit' : 'none' }}>
              {this.renderForm()}
              {this.isAdmin() && <PrimaryC title='新增' style={{ marginBottom: '10px' }} onClick={() => this.handleAddCurb()} />}
              {this.renderCurbTable()}
            </div>
            {pageStatus == 2 && <AddRuleC detailData={record} type={operateType} onCancle={this.onCancle} onOk={this.onOk} changeDetailData={this.changeDetailData} />}
          </div>
        }
      />
    );
  }
}

export default connect(({ limitSetting, dictionaryM, userM: user, loading, globalM }) => ({
  limitSetting,
  dictionaryM,
  user,
  loading,
  globalM,
}))(LimitSetting);
